<template>
  <section id="mySelect">
    <ul class="tab">
      <li v-for="(item,index) in selectList" :class="tabIndex == item ? 'active' : ''" @click="switchSelect(item,index)" :key="index">
        <img   src="../assets/image/unselected1.png" width="13" height="13" v-if="item === '自选'">
        <img :class="tabIndex === '自选' ? 'use_Select':'' " src="../assets/image/selected1.png" width="13" height="13" v-if="item === '自选' && tabIndex === '自选'">
        {{item}}
        </li>
    </ul>
    <section class="table">
     
          <div class="title">
              <div>产品 (点差)</div>
              <div>最新价</div>
              <div>涨跌幅</div>
          </div>
          <div class="content" v-if='tabIndex!="自选"'>
            <template v-if='lists.symbolList && lists.symbolList.length'>
              <div   v-for="(item,i) in lists['symbolObj'][tabIndex]['goods_list']"  :key="i">
                  <div   > 
                    <img @click="addSymbol(item.id)" v-if="defaultSymbol.indexOf(item.id)  ==-1  ?  true:false" src="../assets/image/unselected1.png" width="13" height="13">
                    <img @click="cancelSymbol(item.id)" v-else src="../assets/image/selected1.png" alt=""  width="13" height="13">
                    <a  @click="getDital(item.system_code,item.inAndOut.new_price)" href="javascript:;">{{item.goods_name}} ({{item.inAndOut.difference}})</a>
                  </div>
                  <div @click="getDital(item.system_code,item.inAndOut.new_price)" >{{item.inAndOut.new_price}}</div>
                  <div @click="getDital(item.system_code,item.inAndOut.new_price)" :class="countUpsAndDowns(item.inAndOut.new_price,item.yest_close_price)>=0 ? 'red':'green'"
                    >{{ratioCalculate(item.inAndOut.new_price,item.yest_close_price)}}</div>
              </div>
            </template>
              
          </div>
          <div  class="content" v-else>
            <template v-if=' lists[0].inAndOut.difference'>
                <div    v-for="(item,i) in lists" :key="i">
                    <div  >
                          <img  @click="cancelSymbol(item.id)" src="../assets/image/selected1.png" alt=""  width="13" height="13">
                      <a  @click="getDital(item.system_code,item.inAndOut.new_price)"  href="javascript:;">{{item.goods_name}} ({{item.inAndOut.difference}})</a>
                    </div>
                    <div  @click="getDital(item.system_code,item.inAndOut.new_price)" >{{item.inAndOut.new_price}}</div>
                    <div    @click="getDital(item.system_code,item.inAndOut.new_price)"  :class="countUpsAndDowns(item.inAndOut.new_price,item.yest_close_price)>=0 ? 'red':'green'"
                      >{{ratioCalculate(item.inAndOut.new_price,item.yest_close_price)}}</div>
                </div>
            </template>
            
          </div>
    
    </section>
     <base-alert :bol.sync="alertBol" :type.sync="alertType"></base-alert>
  </section>
</template>
<script>
import {
    _getSymbolTypeList,
    _getSymbolList,
    _getUserSymbolList,
    _getDefaultSymbolList,
    _addSymbolToUser,
    _deleteSymbolFromUser
    } from '../axios/index.js'

export default {
  data() {
    return {
      tabIndex:'外汇',
      symboId:null,
      selectList:['自选','外汇','商品','数字货币','指数'],
      defaultSymbol:[],
      userSymbol:[], //用户自选商品
      logoState:false, //登录状态 
      alertType:1,//弹窗类型
      alertBol:false,// 弹窗
    }
  },
  created(){
       // 系统默认自选
      this.getSymbolTypeListAction();
      this.defaultSymbolList();
  },
  watch:{
    //切换图表库商品
    symboId(){
      //  const $store=this.$store.state.traViewEvent;
      //  localStorage.setItem('symbol',this.symboId)
      //  this.$store.state.pricescale.num=100000;
      // //  this.getFloat(this.lists)


      //  $store.upSymbol(this.symboId)
    }
  },
  methods:{
      alterChoose(type){
         this.alertType=type;
         this.alertBol=true;
     },
    //更改图表库商品
     getDital(symbol,newsPrice){
        //更改图表价格小数点
        this.getKlineFloat(newsPrice)
        //tv事件集合
         const $store=this.$store.state.traViewEvent;
         this.symboId=symbol
         this.$store.state.traViewSymboId=symbol
        //缓存浏览商品
         localStorage.setItem('symbol',this.symboId)
        //更改图表库显示商品
        $store.upSymbol(this.symboId)
     },
     //更改图表价格小数点
    getKlineFloat(newsPrice){
        //取小数
        let  lent=this.getFloat(newsPrice)
        //小数列表
        let  floatList=[100,10,100,1000,10000,100000,1000000,10000];
        //列表长度
        let  _flentg=floatList.length-1;
        //小数大于列表长度侧默认小数位数
        lent> _flentg ? lent=floatList[_flentg]:lent=floatList[lent]
        //缓存小数信息
        localStorage.setItem('pricescale',lent)
        //修改小数引用对象
        this.$store.state.pricescale.num=lent;
     },
      // 用户添加自选
     async addSymbol(goods_id){
         const $store=this.$store.state
         let uid = $store.user 
         if(uid.id) {}
         else uid=localStorage.getItem('user') !=null ? localStorage.getItem('user').id:''
         
         if(uid==''){
              this.alterChoose(2)
              return;
         }
         const res = await _addSymbolToUser(uid.id,goods_id,{user:'loading'})
         if(res.data.code==200){
           //该商品添加到商品列表中
           this.defaultSymbol.push(goods_id)
           this.$Message.success(res.data.msg);
         }else{
           this.$Message.success(res.data.msg);
         }
         
     },
     // 用户取消自选
     async cancelSymbol(goods_id){
        const $store=this.$store.state
        let uid = $store.user 
        if(uid.id) {}
        else uid=localStorage.getItem('user') !=null ? localStorage.getItem('user').id:''
        if(uid==''){
               this.alterChoose(2);
              return;
        }
         //  if(!goods_id && !uid) return;
         
        const res = await _deleteSymbolFromUser(uid.id,goods_id,{user:'loading'});
        if (res.data.code === 200) {
            let data=[];
            //即被删的商品键值
            let key=this.defaultSymbol.indexOf(goods_id);
            //过滤该商品
            for(let i=0;i<this.defaultSymbol.length;i++){
                 if(i==key){
                     
                 }else data.push(this.defaultSymbol[i])
            }
            //新的商品列表
           this.defaultSymbol=data;
           this.$Message.success(res.data.msg);
        }else{
           this.$Message.success(res.data.msg);
         }
    },
   //计算涨跌
   countUpsAndDowns(newsPrice,closePrice){
      var maxPrice=(Number(newsPrice)-Number(closePrice)).toFixed(this.getFloat(closePrice,true));
      maxPrice=maxPrice>=0?'+'+maxPrice:maxPrice;
      return maxPrice;
   },
   // 系统默认推荐自选
   async defaultSymbolList(){
             let res=await _getDefaultSymbolList();
             let data=res.data.data
             for(let i=0;i<data.length;i++){
                 //商品列表
                 this.defaultSymbol.push(data[i])
             }
   },
   // 用户自选商品列表
   async getUserSymbolList(){
        const $store=this.$store.state
        if(!$store.user && !localStorage.getItem('token')){
           return;
        }
        let res=await _getUserSymbolList($store.user.id);
        if(res.data.code==200){
            let data=res.data.data;
            for(let i=0;i<data.length;i++){
            //系统默认 + 用户自选 .
                this.defaultSymbol.push(data[i])
            //用户自选商品
                this.userSymbol.push(data[i])
            };
        }
      },
     // 计算涨幅
    ratioCalculate(price, yclose) {
          let bili = 0;
          if (Number(yclose) != 0) {
            bili = (
              ((Number(price) - Number(yclose)) / Number(yclose)) *
              100
            ).toFixed(2);
    
            if (bili > 0) {
              bili = "+" + bili;
            }
          }
         return bili + "%";
    },
     //获取小数位数
    getFloat(val, bol) {
      let _self = this;
      let _default = bol ? 0 : 1;

      let maxVal =
        String(val).split(".").length == 2
          ? val.split(".")[1].length
          : _default; // 最小变化单位
      return maxVal;
    },
    //选择商品分类
    switchSelect(item,index) {
      let _self = this;
      _self.tabIndex = item;
    },
    //退出登录更改自选列表数据
    outRemUserSyb(data){
      this.defaultSymbol=data;
    },
   // 触发获取商品类别列表的请求
   async getSymbolTypeListAction() {
       const $store = this.$store;
       let res = await _getSymbolTypeList();
       if (res.data.code == 200) {
           $store.state.symbolTypeList = res.data.data;
           // 商品详情列表的请求
           this.getSymbolListAction();
       } else console.error(`获取商品列表类型接口状态${res.data.code}`)
   },
   // 触发获取商品详情列表的请求
   async getSymbolListAction() {
       const $store = this.$store;
       let res = await _getSymbolList();
       if (res.data.code == 200) {
           $store.state.symbolList = res.data.data;
           for (const iterator of $store.state['symbolTypeList']) {
               //获取商品类型索引
               $store.state.symbolObj[iterator.type_name] = null;
           }
           for (const iterator of $store.state['symbolList']) {
               //为已有商品类型索引，存ru商品列表。
               $store.state.symbolObj[iterator.type_name] !== undefined ?
                   $store.state.symbolObj[iterator.type_name] = iterator : '';
          
           }
          

       } else console.error(`获取商品详情列表接口状态${res.data.code}`)

   },
  },
  computed:{
      lists(){
        if(this.$store.state.detialTab!=null){
             this.tabIndex=this.$store.state.detialTab
        console.log(0)

             this.$store.state.detialTab=null;
        }
           // 监听对象
           let symbol=this.$store.state;
           //登录成功
           if(symbol.user && symbol.token && !this.logoState){
             //获取用户自选列表
              this.getUserSymbolList();
             //修改登陆状态
              this.logoState=!0;
           }
           //退出登录
           else if((!symbol.user || !symbol.token) &&  this.logoState && this.userSymbol.length){
               //刷新组件
               this.$store.commit("setIsLogin", true);
           };
           if(this.tabIndex!='自选')  return symbol
           else{
             //筛选出与自选商品数组一致的数据,
             let defSymb=this.defaultSymbol;
             let defSymblist=[];
             for(let i=0;i<symbol.symbolList.length;i++){
               const tabIndex=symbol.symbolList[i].type_name;
                   for(let j=0;j<symbol.symbolObj[tabIndex]['goods_list'].length;j++){
                      const symb=symbol.symbolObj[tabIndex]['goods_list'][j];
                      for(let k=0;k<defSymb.length;k++){
                           if(defSymb[k]==symb.id){
                                 defSymblist.push(symb)
                           }
                      }
                   }
             }
             return defSymblist
           }
       },
   }
}
</script>
